package com.cisystem.web.controller.business;

import com.cisystem.common.config.CiSystemConfig;
import com.cisystem.common.core.controller.BaseController;
import com.cisystem.common.core.domain.AjaxResult;
import com.cisystem.common.core.domain.model.LoginUser;
import com.cisystem.common.exception.base.BaseException;
import com.cisystem.common.utils.SecurityUtils;
import com.cisystem.common.utils.StringUtils;
import com.cisystem.framework.web.service.PermissionService;
import com.cisystem.framework.web.service.SysPermissionService;
import com.cisystem.framework.web.service.TokenService;
import com.cisystem.system.domain.FileDir;
import com.cisystem.system.domain.FileStore;
import com.cisystem.system.domain.vo.assign.AssignEmailDataRequest;
import com.cisystem.system.service.IFileDirService;
import com.cisystem.system.service.IFileStoreService;
import com.cisystem.system.service.ISysUserService;
import com.cisystem.system.service.impl.SysMenuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

@RestController
@RequestMapping("/business/first")
public class FirstController extends BaseController {

    @Autowired
    SysMenuServiceImpl menuService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    TokenService tokenService;

    @Autowired
    SysPermissionService sysPermissionService;


    @Autowired
    IFileDirService fileDirService;

    @Autowired
    ISysUserService userService;

    @Autowired
    PdfController pdfController;

    @Autowired
    IFileStoreService fileStoreService;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:first:list')")
    public AjaxResult listPdfFiles(String filePath) throws FileNotFoundException {
        Map<String, Object> subMap = new HashMap<>();
        subMap.put("files", new ArrayList<String>());
        subMap.put("dir", new ArrayList<HashMap<String, Object>>());
        subMap.put("path", filePath);
        readFile(subMap);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> permissions = loginUser.getPermissions();
        if (permissionService.hasPermissions(permissions,"")){
            // 如果有所有权限，直接返回
            return success(subMap);
        }else{
            String prefix = "business:firstfile:";
            List<Map<String, Object>> dirs = (List<Map<String, Object>>)subMap.get("dir");
            List<Map<String, Object>> newDirs = new ArrayList<>();
            if (CollectionUtils.isEmpty(dirs)){
                return success(subMap);
            }
            //获取权限文件夹
            for (String permission : permissions) {
                // 判断是否是文件夹相关的权限
                if (permission.startsWith(prefix)){
                    // 获取文件夹名称
                    String fireDir = permission.substring(prefix.length());
                    // 获取指定文件夹
                    for (Map<String, Object> dir : dirs) {
                        String path = (String) dir.get("path");
                        String[] split = path.split("\\\\");
                        String dirName = split[split.length - 1];
                        if (fireDir.equals(dirName)){
                            newDirs.add(dir);
                        }
                    }
                }
            }
            subMap.put("dir",newDirs);
            return success(subMap);
        }
    }
    /**
     * 获取所有的可以分配的人员
     */
    @GetMapping("/getAssignSource/{fileId}")
    @PreAuthorize("@ss.hasPermi('business:first:assign')")
    public AjaxResult getAssignSource(@PathVariable("fileId") String fileId){
       return pdfController.getAssignSourcePublic(fileId);
    }
    /**
     * 发送邮件通知,生成记录
     */
    @PostMapping("/assignEmail")
    @PreAuthorize("@ss.hasPermi('business:first:assign')")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult assignEmail(@RequestBody AssignEmailDataRequest request){
        return pdfController.assignEmailPublic(request);
    }
    /**
     * 获取first的文件ID
     */
    @GetMapping("/getFirstDirId")
    @PreAuthorize("@ss.hasPermi('business:first:list')")
    public AjaxResult getFirstDirId(){
        FileDir fileDir = new FileDir();
        List<FileDir> fileDirs = fileDirService.selectFileDirList(fileDir);
        if (CollectionUtils.isEmpty(fileDirs)){
            return AjaxResult.error("没有文件目录");
        }
        FileDir fileDir1 = fileDirs.stream().filter(i -> "0".equals(i.getFartherId()) && i.getFolderPath().startsWith(CiSystemConfig.getCopyFirstPath())).findAny().orElse(null);
        if (fileDir1 == null){
            return AjaxResult.error("没有根目录");
        }
        return success(fileDir1);
    }
    /**
     * 获取文件权限配置
     */
    @GetMapping("/getFirstConfig")
    @PreAuthorize("@ss.hasPermi('business:first:config')")
    public AjaxResult getFirstConfig(){
        return success(menuService.selectFileDirConfig("business:firstfile:"));
    }
    /**
     * 添加文件权限配置
     */
    @GetMapping("/addFirstConfig")
    @PreAuthorize("@ss.hasPermi('business:first:config')")
    public AjaxResult addFirstConfig(String fileDirName){
        return success(menuService.addFileDirConfig("business:firstfile:",fileDirName));
    }
    /**
     * 删除文件权限配置
     */
    @GetMapping("/deleteFirstConfig")
    @PreAuthorize("@ss.hasPermi('business:first:config')")
    public AjaxResult deleteFirstConfig(Long menuId){
        menuService.deleteMenuById(menuId);
        // 更新缓存用户权限
        LoginUser loginUser = getLoginUser();
        if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
        {
            loginUser.setPermissions(sysPermissionService.getMenuPermission(loginUser.getUser()));
            loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
            tokenService.setLoginUser(loginUser);
        }
        return success();
    }
    /**
     * 读取某个文件夹下的所有文件
     *
     */
    @SuppressWarnings("unchecked")
    public void readFile(Map<String, Object> map) throws FileNotFoundException {
        try {
            List<String> files = (List<String>) map.get("files");
            List<Map<String, Object>> dir = (List<Map<String, Object>>) map.get("dir");
            String filepath = (String) map.get("path");
            File file = new File(filepath);
            // 如果这个文件不是目录，则进行如下操作
            if (!file.isDirectory()) {
                files.add(file.getPath());
            } else if (file.isDirectory()) {
                String[] fileList = file.list();
                if (fileList == null) {
                    return ;
                }
                for (String s : fileList) {
                    File readfile = new File(filepath + "\\" + s);
                    if (!readfile.isDirectory()) {
                        files.add(readfile.getPath());
                    } else if (readfile.isDirectory()) {
                        Map<String, Object> subMap = new HashMap<>();
                        subMap.put("files", new ArrayList<String>());
                        subMap.put("dir", new ArrayList<HashMap<String, Object>>());
                        subMap.put("path", readfile.getPath());
                        dir.add(subMap);
                        readFile(subMap);
                    }
                }
            }
        } catch (FileNotFoundException e) {
           throw new BaseException("读取文件路径出错！");
        }
    }
    /**
     * 修改文件隐藏状态
     */
    @GetMapping("/editVisible/{fileId}/{visible}")
    @PreAuthorize("@ss.hasPermi('business:first:visible')")
    public AjaxResult editVisible(@PathVariable("fileId") String fileId,@PathVariable("visible") String visible){
        fileStoreService.editVisible(fileId,visible);
        return success();
    }
}